// 动画系统（改进版）
export class AnimationSystem {
    constructor() {
        this.animationDuration = 800; // 动画持续时间
        this.liftHeight = 20; // 上移高度
    }

    async animatePour(fromTubeId, toTubeId) {
        const fromTube = document.querySelector(`[data-tube-id="${fromTubeId}"]`);
        const toTube = document.querySelector(`[data-tube-id="${toTubeId}"]`);
        
        if (!fromTube || !toTube) return;

        // 获取试管位置
        const fromRect = fromTube.getBoundingClientRect();
        const toRect = toTube.getBoundingClientRect();
        
        // 计算移动方向
        const direction = fromRect.left < toRect.left ? 'right' : 'left';
        
        // 创建动画容器
        const animationContainer = document.createElement('div');
        animationContainer.className = 'pour-animation-container';
        animationContainer.style.cssText = `
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            pointer-events: none;
            z-index: 1000;
        `;
        document.body.appendChild(animationContainer);

        // 克隆源试管用于动画
        const animatedTube = fromTube.cloneNode(true);
        animatedTube.style.cssText = `
            position: absolute;
            left: ${fromRect.left}px;
            top: ${fromRect.top}px;
            width: ${fromRect.width}px;
            height: ${fromRect.height}px;
            transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
            z-index: 1001;
            transform-origin: bottom center;
        `;
        animationContainer.appendChild(animatedTube);

        // 隐藏原始试管
        fromTube.style.opacity = '0.3';
        toTube.style.opacity = '0.3';

        try {
            // 第一步：上移试管（如果还没有上移）
            if (!fromTube.classList.contains('selected')) {
                await this.animateTubeMovement(animatedTube, 'lift');
            }
            
            // 第二步：平移到目标位置
            await this.animateTubeMovement(animatedTube, 'move', toRect, direction);
            
            // 第三步：倾斜试管
            await this.animateTubeMovement(animatedTube, 'tilt', null, direction);
            
            // 第四步：液体流动效果
            await this.animateLiquidFlow(animatedTube, toTube, direction);
            
            // 第五步：试管复位
            await this.animateTubeMovement(animatedTube, 'reset');
            
            // 第六步：移动回原位置
            await this.animateTubeMovement(animatedTube, 'return', fromRect);
            
        } finally {
            // 清理动画元素
            document.body.removeChild(animationContainer);
            fromTube.style.opacity = '1';
            toTube.style.opacity = '1';
        }
    }

    async animateTubeMovement(tubeElement, action, targetRect = null, direction = 'right') {
        return new Promise(resolve => {
            const duration = 300;
            
            switch (action) {
                case 'lift':
                    // 上移试管
                    tubeElement.style.transform = `translateY(-${this.liftHeight}px) scale(1.1)`;
                    break;
                    
                case 'move': {
                    // 平移到目标位置
                    if (targetRect) {
                        const currentRect = tubeElement.getBoundingClientRect();
                        let deltaX;
                        
                        if (direction === 'right') {
                            // 目标试管在右侧，移动到目标试管左边进行倾倒
                            deltaX = targetRect.left - currentRect.right - 10;
                        } else {
                            // 目标试管在左侧，移动到目标试管右边进行倾倒
                            deltaX = targetRect.right - currentRect.left + 10;
                        }
                        
                        tubeElement.style.transform = `translateY(-${this.liftHeight}px) translateX(${deltaX}px) scale(1.1)`;
                    }
                    break;
                }
                    
                case 'tilt': {
                    // 倾斜试管
                    const tiltAngle = direction === 'right' ? 45 : -45;
                    tubeElement.style.transform += ` rotate(${tiltAngle}deg)`;
                    break;
                }
                    
                case 'reset': {
                    // 复位试管（保持在目标位置）
                    const currentTransform = tubeElement.style.transform;
                    const translateMatch = currentTransform.match(/translateX\(([^)]+)\)/);
                    const translateX = translateMatch ? translateMatch[1] : '0px';
                    
                    tubeElement.style.transform = `translateY(-${this.liftHeight}px) translateX(${translateX}) scale(1.1) rotate(0deg)`;
                    break;
                }
                    
                case 'return': {
                    // 返回原位置
                    if (targetRect) {
                        const currentRect = tubeElement.getBoundingClientRect();
                        const deltaX = targetRect.left - currentRect.left;
                        const deltaY = targetRect.top - currentRect.top;
                        
                        tubeElement.style.transform = `translateY(${deltaY}px) translateX(${deltaX}px) scale(1) rotate(0deg)`;
                    }
                    break;
                }
            }
            
            setTimeout(resolve, duration);
        });
    }

    async animateLiquidFlow(fromTube, toTube, direction) {
        return new Promise(resolve => {
            // 创建液体流动效果
            const liquidStream = document.createElement('div');
            liquidStream.className = 'liquid-stream';
            
            const fromRect = fromTube.getBoundingClientRect();
            const toRect = toTube.getBoundingClientRect();
            
            // 根据方向计算流动路径
            let startX, startY, endX, endY;
            
            if (direction === 'right') {
                startX = fromRect.right - 10;
                startY = fromRect.top + fromRect.height * 0.3;
                endX = toRect.left + toRect.width / 2;
                endY = toRect.top + toRect.height * 0.8;
            } else {
                startX = fromRect.left + 10;
                startY = fromRect.top + fromRect.height * 0.3;
                endX = toRect.left + toRect.width / 2;
                endY = toRect.top + toRect.height * 0.8;
            }
            
            liquidStream.style.cssText = `
                position: fixed;
                left: ${startX}px;
                top: ${startY}px;
                width: 4px;
                height: 0px;
                background: linear-gradient(to bottom, 
                    rgba(52, 152, 219, 0.8) 0%,
                    rgba(52, 152, 219, 0.6) 50%,
                    rgba(52, 152, 219, 0.4) 100%);
                border-radius: 2px;
                transform-origin: top center;
                z-index: 1002;
                transition: all 0.5s ease;
            `;
            
            document.body.appendChild(liquidStream);
            
            // 动画液体流动
            setTimeout(() => {
                const distance = Math.sqrt(
                    Math.pow(endX - startX, 2) + Math.pow(endY - startY, 2)
                );
                const angle = Math.atan2(endY - startY, endX - startX) * 180 / Math.PI;
                
                liquidStream.style.height = `${distance}px`;
                liquidStream.style.transform = `rotate(${angle + 90}deg)`;
            }, 50);
            
            // 添加液体滴落效果
            setTimeout(() => {
                this.createLiquidDroplets(startX, startY, endX, endY);
            }, 200);
            
            // 清理液体流
            setTimeout(() => {
                if (liquidStream.parentNode) {
                    liquidStream.parentNode.removeChild(liquidStream);
                }
                resolve();
            }, 600);
        });
    }

    createLiquidDroplets(startX, startY, endX, endY) {
        const dropletCount = 5;
        
        for (let i = 0; i < dropletCount; i++) {
            setTimeout(() => {
                const droplet = document.createElement('div');
                droplet.className = 'liquid-droplet';
                droplet.style.cssText = `
                    position: fixed;
                    left: ${startX + Math.random() * 10 - 5}px;
                    top: ${startY}px;
                    width: 3px;
                    height: 3px;
                    background: rgba(52, 152, 219, 0.7);
                    border-radius: 50%;
                    z-index: 1003;
                    transition: all 0.4s ease-in;
                `;
                
                document.body.appendChild(droplet);
                
                // 动画滴落
                setTimeout(() => {
                    droplet.style.left = `${endX + Math.random() * 20 - 10}px`;
                    droplet.style.top = `${endY}px`;
                    droplet.style.opacity = '0';
                }, 50);
                
                // 清理滴落元素
                setTimeout(() => {
                    if (droplet.parentNode) {
                        droplet.parentNode.removeChild(droplet);
                    }
                }, 500);
            }, i * 100);
        }
    }

    async animateComplete(tubeId) {
        const tube = document.querySelector(`[data-tube-id="${tubeId}"]`);
        if (!tube) return;

        return new Promise(resolve => {
            // 添加完成动画类
            tube.classList.add('complete-animation');
            
            // 创建庆祝效果
            this.createCelebrationEffect(tube);
            
            setTimeout(() => {
                tube.classList.remove('complete-animation');
                resolve();
            }, 1000);
        });
    }

    createCelebrationEffect(tube) {
        const rect = tube.getBoundingClientRect();
        const centerX = rect.left + rect.width / 2;
        const centerY = rect.top + rect.height / 2;
        
        // 创建星星效果
        for (let i = 0; i < 8; i++) {
            const star = document.createElement('div');
            star.className = 'celebration-star';
            star.style.cssText = `
                position: fixed;
                left: ${centerX}px;
                top: ${centerY}px;
                width: 10px;
                height: 10px;
                background: #f1c40f;
                clip-path: polygon(50% 0%, 61% 35%, 98% 35%, 68% 57%, 79% 91%, 50% 70%, 21% 91%, 32% 57%, 2% 35%, 39% 35%);
                z-index: 1500;
                transform-origin: center;
            `;
            
            document.body.appendChild(star);
            
            // 随机方向的星星爆炸效果
            const angle = (i / 8) * 360;
            const distance = 50 + Math.random() * 30;
            const endX = centerX + Math.cos(angle * Math.PI / 180) * distance;
            const endY = centerY + Math.sin(angle * Math.PI / 180) * distance;
            
            setTimeout(() => {
                star.style.left = `${endX}px`;
                star.style.top = `${endY}px`;
                star.style.transform = `scale(1.5) rotate(360deg)`;
                star.style.opacity = '0';
                star.style.transition = 'all 1s ease-out';
            }, 50);
            
            // 清理星星元素
            setTimeout(() => {
                if (star.parentNode) {
                    star.parentNode.removeChild(star);
                }
            }, 1100);
        }
    }

    async animateBottleCap(tubeId) {
        const tube = document.querySelector(`[data-tube-id="${tubeId}"]`);
        if (!tube) return;

        return new Promise(resolve => {
            const bottleCap = tube.querySelector('.bottle-cap');
            if (bottleCap) {
                bottleCap.style.animation = 'bottleCapAppear 0.6s ease-out';
                setTimeout(resolve, 600);
            } else {
                resolve();
            }
        });
    }

    // 选择动画
    async animateSelection(tubeId, selected) {
        const tube = document.querySelector(`[data-tube-id="${tubeId}"]`);
        if (!tube) return;

        return new Promise(resolve => {
            if (selected) {
                tube.classList.add('selecting');
                setTimeout(() => {
                    tube.classList.remove('selecting');
                    tube.classList.add('selected');
                    resolve();
                }, 300);
            } else {
                tube.classList.remove('selected');
                tube.classList.add('deselecting');
                setTimeout(() => {
                    tube.classList.remove('deselecting');
                    resolve();
                }, 300);
            }
        });
    }

    // 移动动画（用于试管重新排列）
    async animateTubeReposition(tubeId, newPosition) {
        const tube = document.querySelector(`[data-tube-id="${tubeId}"]`);
        if (!tube) return;

        return new Promise(resolve => {
            tube.classList.add('moving');
            tube.style.transform = `translate(${newPosition.x}px, ${newPosition.y}px)`;
            
            setTimeout(() => {
                tube.classList.remove('moving');
                tube.style.transform = '';
                resolve();
            }, 500);
        });
    }
}